package com.boomsecret.juc.locks;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author wangjinliang on 2019/1/18.
 */
public class ReentrantLockConditionDemo {
    private static ReentrantLock lock = new ReentrantLock();
    private static Condition condition = lock.newCondition();

    public static void main(String[] args) throws Exception {
        ConditionThread conditionThread = new ConditionThread("tt");
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName()+" start ta");
            conditionThread.start();

            System.out.println(Thread.currentThread().getName()+" block");
            condition.await();

            System.out.println(Thread.currentThread().getName()+" continue");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static class ConditionThread extends Thread {
        public ConditionThread(String name) {
            super(name);
        }

        @Override
        public void run() {
            lock.lock();
            try {
                Thread.sleep(2000);
                System.out.println(Thread.currentThread().getName()+" wakeup others");
                condition.signal();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }
}
